package com.starview.star.compiler.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;

/**
 * Utility to help instrument timing
 * 
 * @author fgm
 */
public class Instrument
{
  public static final double NANOS_PER_SECOND = 1.0e9;
  public static final long NANOS_PER_MILLI = 1000000;

  private final String title;
  private final long start;
  private final List<Pair<String, Long>> timeSlots = new ArrayList<>();
  private long lastTime;

  public Instrument(String title)
  {
    this.title = title;
    this.start = lastTime = System.nanoTime();
  }

  public void record(String subtitle)
  {
    long mark = System.nanoTime();
    long delta = mark - lastTime;
    lastTime = mark;
    timeSlots.add(Pair.pair(subtitle, delta));
  }

  public String report()
  {
    return report("total ");
  }

  public String report(String msg)
  {
    StringBuilder report = new StringBuilder();

    report.append(title);
    report.append("\n");

    for (Entry<String, Long> entry : timeSlots) {
      long secs = entry.getValue() / NANOS_PER_MILLI;
      report.append(entry.getKey()).append(" ").append(Long.toString(secs)).append(" millisecs\n");
    }

    double total = ((double) (lastTime - start)) / 1.0e9;
    report.append(msg).append(Double.toString(total)).append("secs\n");

    return report.toString();
  }
}
